package cn.yeziji.file.handler.service;

import cn.yeziji.file.basic.MinioProperties;
import cn.yeziji.file.service.FileService;
import cn.yeziji.file.service.impl.FileServiceImpl;
import cn.yeziji.file.utils.FileHandlerUtils;
import cn.yeziji.forum.common.key.CommonKey;
import cn.yeziji.forum.basic.file.OssRequiredEntry;
import cn.yeziji.forum.utils.SpringUtils;
import cn.yeziji.forum.utils.StrUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.InputStream;

/**
 * 文档类型
 *
 * @author gzkemays
 * @since 2022/11/03 11:46 PM
 */
@Slf4j
public class DocsSelected implements TypeSelected {
  String filename;

  public DocsSelected(String filename) {
    this.filename = filename;
  }

  @Override
  public Object types(String type) {
    // 从 spring 容器中获取指定类
    FileService fileService = SpringUtils.getBean(FileServiceImpl.class);
    MinioProperties properties = SpringUtils.getBean(MinioProperties.class);
    // 获取基本参数
    String ext = StrUtils.getLastSplitHasSplitAfterStr(filename, CommonKey.DOT);
    String filePath = properties.getSavePath() + File.separator + filename;
    if (ext.equals(PDF)) {
      // 如果是 pdf 则需要生成缩略图并返回图片地址
      File file = new File(filePath);
      // 绘画图片并写入 stream
      InputStream thumbStream = FileHandlerUtils.generatePDFImageStream(file);
      String thumbName = "thumb-" + filename.replace(ext, ".jpg");
      log.info("开始上传缩略图");
      String thumbUrl = fileService.oss(new OssRequiredEntry(DOCS_PATH, thumbName, thumbStream));
      log.info("上传缩略图完毕 -> {}", thumbUrl);
      return thumbUrl;
    }
    return null;
  }
}
